package com.ytjj.qmyx.admin.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.github.wxpay.sdk.WXPayUtil;
import com.google.common.collect.Lists;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.api.ResultCode;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.exception.GlobalExceptionHandler;
import com.ytjj.common.model.ExposureNumResponse;
import com.ytjj.common.model.FileResponse;
import com.ytjj.common.model.request.AliPayOrderSyncRequest;
import com.ytjj.common.model.response.OrdersPayResponse;
import com.ytjj.common.utils.AliyunOSSClientUtil;
import com.ytjj.common.utils.HttpClientUtil;
import com.ytjj.qmyx.admin.annotation.OperLog;
import com.ytjj.qmyx.admin.client.BankerClient;
import com.ytjj.qmyx.admin.config.SupplyApiConfig;
import com.ytjj.qmyx.admin.constants.SysLogConstants;
import com.ytjj.qmyx.admin.dao.CustomerDao;
import com.ytjj.qmyx.admin.model.Admin;
import com.ytjj.qmyx.admin.model.banker.OrderExceptionNoteReq;
import com.ytjj.qmyx.admin.model.dto.SonOrderDto;
import com.ytjj.qmyx.admin.model.request.*;
import com.ytjj.qmyx.admin.model.response.ImportExcelFailResponse;
import com.ytjj.qmyx.admin.model.response.OrdersInfoResponse;
import com.ytjj.qmyx.admin.model.response.TwoOrdersResponse;
import com.ytjj.qmyx.admin.service.MemberService;
import com.ytjj.qmyx.admin.service.OrdersService;
import com.ytjj.qmyx.admin.utils.AESUtil;
import com.ytjj.qmyx.admin.utils.UserUtil;
import com.ytjj.qmyx.mall.client.MallClient;
import com.ytjj.qmyx.mall.mapper.OrdersInfoMapper;
import com.ytjj.qmyx.mall.mapper.OrdersMapper;
import com.ytjj.qmyx.mall.mapper.OrdersPayMapper;
import com.ytjj.qmyx.mall.model.OrderExpressModifiedRequest;
import com.ytjj.qmyx.mall.model.Orders;
import com.ytjj.qmyx.mall.model.OrdersInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单管理
 *
 *
 * @version 1.0
 *
 */
@RestController
@RequestMapping("order")
@Slf4j
public class OrderController extends GlobalExceptionHandler {
    @Resource
    private BankerClient bankerClient;
    @Resource
    private final OrdersService ordersService;
    @Resource
    private OrdersMapper ordersMapper;
    @Resource
    private OrdersInfoMapper ordersInfoMapper;
    @Resource
    private SupplyApiConfig supplyApiConfig;
    @Resource
    private MemberService memberService;

    @Resource
    private OrdersPayMapper ordersPayMapper;

    @Resource
    private MallClient mallClient;
    @Resource
    private CustomerDao customerDao;

    public OrderController(OrdersService ordersService) {
        this.ordersService = ordersService;
    }

    /**
     * 获取订单列表
     *
     * @param request
     * @return
     */
    @RequiresPermissions("order:getOrdersList")
    @PostMapping("/getOrdersList")
    public CommonResult getOrdersList(@RequestBody OrdersRequest request) {
        //非管理员只允许查询最近3个月数据
        if(!UserUtil.isAdmin()) {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, -3);
            if(request.getStartTime()!=null){
                if(calendar.getTime().compareTo(request.getStartTime())>0){
                    request.setStartTime(calendar.getTime());
                }
            }else{
                request.setStartTime(calendar.getTime());
            }
        }
        CommonPage<Orders> commonPage=ordersService.getOrdersList(request);
        if(!UserUtil.isAdmin()) {
            commonPage.getList().stream().forEach(item -> {
                item.setChannel("");
                item.setOrderSource("");
            });
        }
        return CommonResult.success(commonPage);
    }

    /**
     * 获取订单列表缩减版
     *
     * @param request
     * @return
     */
    @RequiresPermissions("common:orderList")
    @PostMapping("/getOrdersListCurtail")
    public CommonResult getOrdersListCurtail(@RequestBody OrdersRequest request) {
        //非管理员只允许查询最近3个月数据
        if(!UserUtil.isAdmin()) {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, -3);
            if(request.getStartTime()!=null){
                if(calendar.getTime().compareTo(request.getStartTime())>0){
                    request.setStartTime(calendar.getTime());
                }
            }else{
                request.setStartTime(calendar.getTime());
            }
        }
        CommonPage<OrdersInfoResponse> commonPage=ordersService.getOrdersListCurtail(request);
        return CommonResult.success(commonPage);
    }

    /**
     * 获取二类订单列表
     * @param request
     * @return
     */
    @PostMapping("/getTwoOrdersList")
    public CommonResult getTwoOrdersList(@RequestBody OrdersRequest request) {
        //非管理员只允许查询最近3个月数据
        if(!UserUtil.isAdmin()) {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, -3);
            if(request.getStartTime()!=null){
                if(calendar.getTime().compareTo(request.getStartTime())>0){
                    request.setStartTime(calendar.getTime());
                }
            }else{
                request.setStartTime(calendar.getTime());
            }
        }
        List<TwoOrdersResponse> list=ordersService.getTwoOrdersList(request);
        if(!UserUtil.isAdmin()) {
            list.stream().forEach(item -> {
                item.setChannel("");
                item.setOrderSource("");
            });
        }
        return CommonResult.page(list);
    }

    /**
     * 更改单条订单信息
     */
    @GetMapping("/fillOrderExpress")
    public CommonResult fillOrderExpress(@RequestParam("orderId") Integer orderId,
                                         @RequestParam("expressCompanyNo") String expressCompanyNo,
                                         @RequestParam("expressNo") String expressNo,
                                         @RequestParam("express") String express) {
            if(StringUtils.isEmpty(express)){
                return CommonResult.success(ordersService.fillOrderExpress(orderId, expressCompanyNo, expressNo,null) && ordersService.insertExpress(orderId, expressCompanyNo,expressNo,null));
            }
            return CommonResult.success(ordersService.fillOrderExpress(orderId, expressCompanyNo, expressNo,null)&& ordersService.fillOrder(expressCompanyNo,expressNo,express,null));
    }
    /**
     * 导入快递单号
     */
    @PostMapping("batchImportTwoOrderList")
    public CommonResult batchImportTwoOrderList(MultipartFile file) throws IOException {
            // 上传到oss
            this.getImgUrl(file);
            // 导入订单
            Sheet sheet = new Sheet(1, 1, TwoOrderRequest.class);
            try {
                List<Object> list = EasyExcelFactory.read(new BufferedInputStream(file.getInputStream()), sheet);
                ordersService.batchInsertOrders(list.stream()
                        .map(item -> (TwoOrderRequest) item)
                        .collect(Collectors.toList()));
                return CommonResult.success(ResultCode.SUCCESS);
            } catch (IOException e) {
                e.printStackTrace();
                log.error("导入发生异常：{}", e.getMessage());
            }
            return CommonResult.failed(ResultCode.FAILED);
    }

    /**
     * @Description 上传文件
     *
     *
     * @Version 1.0
     **/
    public FileResponse getImgUrl(MultipartFile file) {
        if (file.isEmpty()) {
            throw new ApiException("文件不存在");
        }
        // 初始化OssClient
        OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();
        FileResponse fileResponse = AliyunOSSClientUtil.uploadObject2OSS(ossClient, file);
        if (fileResponse == null) {
            throw new ApiException("文件上传失败");
        }
        return fileResponse;
    }


    /**
     * 批量导出二类订单列表
     *
     * @param request
     * @return
     */
    @PostMapping("/batchExportTwoOrderList")
    public CommonResult batchExportTwoOrderList(@RequestBody OrdersRequest request) {
        return CommonResult.success(ordersService.batchExportTwoOrderList(request));
    }


    /**
     * @Description 获取订单详情
     *
     *
     *
     * @Version 1.0
     **/
    @RequiresPermissions("order:getOrderDetail")
    @GetMapping("/getOrderDetail")
    public CommonResult getOrderDetail(@RequestParam("orderId") Integer orderId) {
        return CommonResult.success(ordersService.getOrderDetail(orderId));
    }

    /**
     * @Description 获取订单详情缩减版
     *
     *
     *
     * @Version 1.0
     **/
    @RequiresPermissions("commonNew:orderDetail")
    @GetMapping("/getOrderDetailCurtail")
    public CommonResult getOrderDetailCurtail(@RequestParam("orderId") Integer orderId) {
        return CommonResult.success(ordersService.getOrderDetailCurtail(orderId));
    }


    /**
     * 更改物流信息
     * @param orderAddressRequest
     * @return
     */
    @PostMapping("/updateOrderInfo")
    public CommonResult updateOrderInfo(@RequestBody OrderAddressRequest orderAddressRequest) {
        ordersService.updateOrderInfo(orderAddressRequest);
        return CommonResult.success(ResultCode.SUCCESS);
    }

    @GetMapping("/getExpressDicList")
    public CommonResult getExpressDicList() {
        return CommonResult.success(ordersService.getExpressDicList());
    }

    /**
     * 订单小记
     *
     * @param content
     * @return
     */
    @RequiresPermissions("order:writeRecord")
    @GetMapping("/writeRecord")
    @OperLog(operModule = "订单模块", operDesc = "订单小记", operType = SysLogConstants.OPERATION_UPDATE)
    public CommonResult writeRecord(@RequestParam("content") String content,
                                    @RequestParam("orderId") Integer orderId) {
        ordersService.writeRecord(content, orderId);
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
     * 获取订单明细列表缩减版
     *
     * @return public static List<Object> read(InputStream in, Sheet sheet) {
     */
    @RequiresPermissions("commonOrder:detail")
    @PostMapping("/getOrdersInfoListCurtail")
    public CommonResult getOrdersInfoListCurtail(@RequestBody OrdersInfoRequest request) {
        return CommonResult.success(ordersService.getOrdersInfoListCurtail(request));
    }

    /**
     * 获取订单明细列表
     *
     * @return public static List<Object> read(InputStream in, Sheet sheet) {
     */
    @RequiresPermissions("order:getOrdersList")
    @PostMapping("/getOrdersInfoList")
    public CommonResult getOrdersInfoList(@RequestBody OrdersInfoRequest request) {
        //非管理员只允许查询最近3个月数据
        String email=UserUtil.getPrincipal();
        if(!UserUtil.isAdmin()) {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, -3);
            if(request.getStartTime()!=null){
                if(calendar.getTime().compareTo(request.getStartTime())>0){
                    request.setStartTime(calendar.getTime());
                }
            }else{
                request.setStartTime(calendar.getTime());
            }
        }
        CommonPage<OrdersInfoResponse> commonPage=ordersService.getOrdersInfoList(request);
        if(!UserUtil.isAdmin()) {
            commonPage.getList().stream().forEach(item -> {
                if("likui@qmyx.com".equalsIgnoreCase(email)){//app运营主管
                    if("h5".equalsIgnoreCase(item.getOrderSource())){
                        item.setChannel("");
                    }
                }else {
                    item.setChannel("");
                }
            });
        }
        return CommonResult.success(commonPage);
    }

    /**
     * 批量修改订单快递单号
     * @param file
     * @return
     */
    @RequiresPermissions("order:batchUpdateOrders")
    @PostMapping("/batchUpdateOrders")
    @OperLog(operModule = "订单模块", operDesc = "批量修改订单快递单号", operType = SysLogConstants.OPERATION_UPDATE)
    public CommonResult batchUpdateOrders(MultipartFile file) {
        Sheet sheet = new Sheet(1, 1, OrdersExpressRequest.class);
        try {
            List<Object> list = EasyExcelFactory.read(new BufferedInputStream(file.getInputStream()), sheet);
            return CommonResult.success(ordersService.batchUpdateOrders(list.stream()
                    .map(item -> (OrdersExpressRequest) item).collect(Collectors.toList())));
        } catch (IOException e) {
            e.printStackTrace();
            log.error("导入发生异常：{}", e.getMessage());
        }
        return CommonResult.failed();
    }

    /**
     * 导出excel 前端导出
     *
     * @param request
     * @return
     * @throws IOException
     */
    @RequiresPermissions("order:exportOrdersExcel")
    @PostMapping("exportOrdersExcel")
    public CommonResult exportOrdersExcel(@RequestBody OrdersInfoRequest request) {
        //非管理员只允许查询最近3个月数据
        if(!UserUtil.isAdmin()) {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, -3);
            if(request.getStartTime()!=null){
                if(calendar.getTime().compareTo(request.getStartTime())>0){
                    request.setStartTime(calendar.getTime());
                }
            }else{
                request.setStartTime(calendar.getTime());
            }
        }
        List<OrdersInfoResponse> list = ordersService.exportOrdersExcel(request);
        if(!UserUtil.isAdmin()) {
            list.stream().forEach(item -> {
                item.setChannel("");
                item.setOrderSource("");
            });
        }
        return CommonResult.success(list);
    }

    /**
     * 改变导出订单的 "状态" 跟 "时间"
     *
     * @param orderCheackRequest
     * @return
     * @throws IOException
     */
    @PostMapping("/updateOrderCheack")
    @OperLog(operModule = "订单模块", operDesc = "改变导出订单的状态跟时间", operType = SysLogConstants.OPERATION_UPDATE)
    public CommonResult updateOrderCheack(@RequestBody OrderCheackRequest orderCheackRequest) {
        int count = ordersService.updateOrderCheack(orderCheackRequest);
        return CommonResult.success(count);
    }


    /**
     * 发起退款
     *
     * @param orderId
     * @return
     */
    @RequiresPermissions("order:refund")
    @GetMapping("/refundOrders")
    @OperLog(operModule = "订单模块", operDesc = "发起退款", operType = SysLogConstants.OPERATION_ADD)
    public CommonResult refundOrders(@RequestParam("orderId") Integer orderId,
                                     @RequestParam("desc") String desc) {
        ordersService.refundOrders(orderId, desc);
        return CommonResult.success(ResultCode.SUCCESS);
    }

    @GetMapping("/refundOrdersByRpc")
    public String refundOrdersByRpc(@RequestParam("orderId") Integer orderId,
                               @RequestParam("desc") String desc) {
        ordersService.refundOrders(orderId, desc);
        return "200";
    }

    @GetMapping("/sumExposureByDynamicId")
    public ExposureNumResponse sumExposureByDynamicId(@RequestParam Integer dynamicId) {
//        Integer value = adsExposeService.sumExposureByDynamicId(dynamicId);
        ExposureNumResponse response = new ExposureNumResponse();
//        response.setExposureNum(value);
        return response;
    }

    /**
     * 变成无效订单
     *
     * @param orderId
     * @return
     */
    @GetMapping("/editOrdersStatus")
    @OperLog(operModule = "订单模块", operDesc = "变成无效订单", operType = SysLogConstants.OPERATION_UPDATE)
    public CommonResult editOrdersStatus(@RequestParam("orderId") Integer orderId,@RequestParam("orderStatus") String orderStatus) {
        ordersService.editOrdersStatus(orderId, orderStatus);
        return CommonResult.success(ResultCode.SUCCESS);
    }


    /**
     * 微信APP退款异步回调
     *
     * @param request
     * @return
     */
    @PostMapping("/wxAppRefundNotify")
    public String wxAppRefundNotify(HttpServletRequest request) {
        try {
            String result = this.getWxRes(request);
            String xmlBack = "";
            Map<String, String> notifyMap = null;
            try {
                notifyMap = WXPayUtil.xmlToMap(result);         // 调用官方SDK转换成map类型数据

                /** 以下字段在return_code为SUCCESS的时候有返回： **/
                // 加密信息：加密信息请用商户秘钥进行解密，详见解密方式
                String req_info = notifyMap.get("req_info");

                /**
                 * 解密方式
                 * 解密步骤如下：
                 * （1）对加密串A做base64解码，得到加密串B
                 * （2）对商户key做md5，得到32位小写key* ( key设置路径：微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置 )
                 * （3）用key*对加密串B做AES-256-ECB解密（PKCS7Padding）
                 */
                String resultStr = AESUtil.decryptData(req_info,"P7975F4F3CB5ABWF9A2FED4D0M2663L4");

                Map<String, String> aesMap = WXPayUtil.xmlToMap(resultStr);
                String returnCode = notifyMap.get("return_code");//状态
                String outRefundNo = aesMap.get("out_refund_no");//商户订单号
                if (returnCode.equals("SUCCESS")) {
                    if (outRefundNo != null) {
                        ordersService.handleRefund(aesMap);
                        log.info("微信手机退款回调成功订单号:{}", outRefundNo);
                        xmlBack = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                    } else {
                        log.info("微信手机退款回调失败订单号:{}", outRefundNo);
                        xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                    }
                }
                return xmlBack;
            } catch (Exception e) {
                log.error("手机退款回调通知失败", e);
                xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            }
            return xmlBack;
        } catch (Exception e) {
            log.error("微信手机退款失败:{}", e.getMessage());
            String result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            return result;
        }
    }

    /**
     * Adapay 支付退款回调接口
     * @param request
     * @return void
     */
    @PostMapping("/refundCallback")
    public Integer callback(HttpServletRequest request) {
        return ordersService.adapayCallBack(request);
    }

    /**
     * 编辑快递信息
     * @param courierInfosRequest
     * @return
     */
    @RequiresPermissions("order:updateCourier")
    @PostMapping("/updateCourier")
    @OperLog(operModule = "订单模块", operDesc = "编辑快递信息", operType = SysLogConstants.OPERATION_ADD)
    public CommonResult updateCourier(@RequestBody CourierInfosRequest courierInfosRequest) {
        ordersService.updateCourier(courierInfosRequest);
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
     * 获取微信响应
     *
     * @param request
     * @return
     * @throws IOException
     */
    private String getWxRes(HttpServletRequest request) throws IOException {
        String resXml = "";
        InputStream inputStream = request.getInputStream();
        //将InputStream转换成xmlString
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        resXml = sb.toString();
        log.info(resXml);
        return resXml;
    }


    @PostMapping("statusSynchro")
    public CommonResult orderStatusSynchro() {
        //获取所有主订单列表
        List<Orders> ordersList = ordersService.getAllOrder();
        if (!CollectionUtils.isEmpty(ordersList)) {
            ordersList.parallelStream()
                    .filter(item -> item.getOrderStatus() != null)
                    .forEach(item ->{
                        List<OrdersInfo> ordersInfoList = ordersService.getAllOrdersInfoByOrderId(item.getId());
                        if (!CollectionUtils.isEmpty(ordersInfoList)) {
                            ordersInfoList.stream().forEach(childItem ->{
                                ordersService.updateStatusByOrderId(item.getOrderStatus(), item.getId());
                            });
                        }
                    });
        }
        return CommonResult.success(1);
    }

    /**
     * 微信APP退款异步回调
     *
     * @param request
     * @return
     */
    @PostMapping("/wxRechargeRefundNotify")
    public String wxRechargeRefundNotify(HttpServletRequest request) {
        try {
            String result = this.getWxRes(request);
            String xmlBack = "";
            Map<String, String> notifyMap = null;
            try {
                notifyMap = WXPayUtil.xmlToMap(result);         // 调用官方SDK转换成map类型数据

                /** 以下字段在return_code为SUCCESS的时候有返回： **/
                // 加密信息：加密信息请用商户秘钥进行解密，详见解密方式
                String req_info = notifyMap.get("req_info");

                /**
                 * 解密方式
                 * 解密步骤如下：
                 * （1）对加密串A做base64解码，得到加密串B
                 * （2）对商户key做md5，得到32位小写key* ( key设置路径：微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置 )
                 * （3）用key*对加密串B做AES-256-ECB解密（PKCS7Padding）
                 */
                String resultStr = AESUtil.decryptData(req_info,"P7975F4F3CB5ABWF9A2FED4D0M2663L4");

                Map<String, String> aesMap = WXPayUtil.xmlToMap(resultStr);
                String returnCode = notifyMap.get("return_code");//状态
                String outRefundNo = aesMap.get("out_refund_no");//商户订单号
                if (returnCode.equals("SUCCESS")) {
                    if (outRefundNo != null) {
//                        ordersService.handleRefund(aesMap);
                        log.info("微信手机退款回调成功订单号:{}", outRefundNo);
                        log.info("微信手机退款回调成功订单信息:{}", aesMap);
                        xmlBack = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                    } else {
                        log.info("微信手机退款回调失败订单号:{}", outRefundNo);
                        xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                    }
                }
                return xmlBack;
            } catch (Exception e) {
                log.error("手机退款回调通知失败", e);
                xmlBack = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            }
            return xmlBack;
        } catch (Exception e) {
            log.error("微信手机退款失败:{}", e.getMessage());
            String result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            return result;
        }
    }
//----------------------------------==异常订单跟踪页==----------------------------------------------
    /**
     * 异常订单跟踪页--客服管理页查询
     * @param exceptionOrdersRequest
     * @return
     */
    @PostMapping("/getExceptionOrders")
    public CommonResult getExceptionOrders(@RequestBody ExceptionOrdersRequest exceptionOrdersRequest){
        String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/getExceptionOrders",
                JSONObject.toJSONString(exceptionOrdersRequest), supplyApiConfig.getHeadsMap());
        CommonResult commonResult = JSONObject.parseObject(result, CommonResult.class);
        return commonResult;
    }

    /**
     * 供应商异常订单跟踪页--客服管理页导出异常订单
     * @param exceptionOrdersRequest
     * @return
     */
    @PostMapping("/batchExportExceptionOrders")
    public CommonResult batchExportExceptionOrders(@RequestBody ExceptionOrdersRequest exceptionOrdersRequest){
        exceptionOrdersRequest.setShopId(Arrays.asList(supplyApiConfig.getShopId()));
        String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/getAllExceptionOrders",
                JSONObject.toJSONString(exceptionOrdersRequest), supplyApiConfig.getHeadsMap());
        CommonResult commonResult = JSONObject.parseObject(result, CommonResult.class);
        return commonResult;
    }

    /**
     * 供应商异常订单跟踪页--处理异常订单
     * @param exceptionOrdersRequest
     * @return
     */
    @PostMapping("/updateExceptionHandleStatus")
    public CommonResult<List<ImportExcelFailResponse>> updateExceptionHandleStatus(@RequestBody ExceptionOrdersRequest exceptionOrdersRequest){
        Admin admin = memberService.getAdmin();
        if(StringUtils.isEmpty(exceptionOrdersRequest.getHandleNote())){
            throw new ApiException("处理备注不能为空！");
        }
        exceptionOrdersRequest.setStatus((byte) 2);
        exceptionOrdersRequest.setHandlePerson(admin.getName());
        String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/updateExceptionHandleStatus",
                JSONObject.toJSONString(Lists.newArrayList(exceptionOrdersRequest)), supplyApiConfig.getHeadsMap());
        CommonResult commonResult = JSONObject.parseObject(result, CommonResult.class);
        if (org.apache.commons.lang3.StringUtils.isBlank(result)) {
            throw new ApiException("接口出错！");
        } else if (200 != commonResult.getCode()) {
            throw new ApiException(commonResult.getMessage());
        } else {
            List<ImportExcelFailResponse> importExcelFailResponses = JSON.parseArray(JSON.toJSONString(commonResult.getData()), ImportExcelFailResponse.class);
            if(!CollectionUtils.isEmpty(importExcelFailResponses)){
                return CommonResult.failed(JSON.toJSONString(importExcelFailResponses));
            }
        }
        return CommonResult.success();
    }

    /**
     * 供应商异常订单跟踪页--批量更新异常订单处理状态
     * @param req
     * @return
     */
    @PostMapping("/batchUpdateExceptionHandleStatus")
    @OperLog(operModule = "供应链异常订单", operDesc = "异常处理", operType = SysLogConstants.OPERATION_UPDATE)
    public CommonResult batchUpdateExceptionHandleStatus(@RequestBody OrderExceptionNoteReq req){
    	if(req.getIds()!=null && req.getIds().length>99) {
    		return CommonResult.failed("批量处理不能超过100条");
    	}
        String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/batchUpdateExceptionHandleStatus",
                JSONObject.toJSONString(req), supplyApiConfig.getHeadsMap());
//        CommonResult commonResult = JSONObject.parseObject(result, CommonResult.class);
//        return commonResult;
        return CommonResult.success();
    }
    
    
    /**
     * 根据主订单号查询主订单详情
     * @param orderNo 主订单号
     * @return
     */
    @GetMapping("getOrderDetailByOrderNo")
    public CommonResult getOrderDetailByOrderNo(@RequestParam("orderNo") String orderNo){
        return CommonResult.success(ordersService.getOrderDetailByOrderNo(orderNo));
    }

    /**
     * 主订单添加备注
     */
    @GetMapping("updateSmallNote")
    public CommonResult updateSmallNote(@RequestParam("orderNo") String orderNo, @RequestParam("smallNote") String smallNote){
        return CommonResult.success(ordersService.updateSmallNote(orderNo,smallNote));
    }

    @PostMapping("/selectOrderInfoAll")
    public CommonResult selectOrderInfoAll(@RequestBody SonOrderDto sonOrderDto) {
        return CommonResult.success(ordersService.selectOrderInfoAll(sonOrderDto));
    }

    /* ----------------------------------------------------------子订单-------------------------------------------------------- */

    /**
     * 根据子订单号查询子订单详情
     */
    @GetMapping("/getChildOrderDetail")
    public CommonResult getChildOrderDetail(@RequestParam("orderNo") String orderNo,
                                            @RequestParam(value = "childOrderNo",required = false) String childOrderNo,
                                            @RequestParam("orderInfoId") Integer orderInfoId) {
        return CommonResult.success(ordersService.getChildOrderDetail(orderNo, childOrderNo, orderInfoId));
    }

    /**
     * 子订单-确认发货
     */
    @GetMapping("/updateOrderInfoStatus")
    public CommonResult updateOrderInfoStatus(@RequestParam("orderInfoId") Integer orderInfoId,
                                              @RequestParam("orderId") Integer orderId,
                                              @RequestParam("expressCompanyNo") String expressCompanyNo,
                                              @RequestParam("expressNo") String expressNo,
                                              @RequestParam("express") String express){
        Orders orders = ordersMapper.selectByPrimaryKey(orderId);
        if (orders.getIsPay() == 0) {
            return CommonResult.failed("您的订单未支付");
        }
        OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(orderInfoId);
        if(StringUtils.isEmpty(express)){
            boolean b = ordersService.fillOrderExpress(orderId, expressCompanyNo, expressNo, orderInfoId);
            ordersService.insertExpress(orderId, expressCompanyNo,expressNo,orderInfoId);
            if (b == true) {
                try {
                    ordersService.updateOrderExpressInfo(ordersInfo.getChildOrderNo(),expressCompanyNo,expressNo);
                } catch (Exception e) {
                    log.error("======同步供应商快递单号异常======{}",e);
                }
            }
            return ordersService.updateOrderInfoStatus(orderInfoId);
        }
        boolean b = ordersService.fillOrderExpress(orderId, expressCompanyNo, expressNo, orderInfoId);
        ordersService.fillOrder(expressCompanyNo,expressNo,express,orderInfoId);
        if (b == true) {
            try {
                ordersService.updateOrderExpressInfo(ordersInfo.getChildOrderNo(),expressCompanyNo,expressNo);
            } catch (Exception e) {
                log.error("======同步供应商快递单号异常======{}",e);
            }
        }
        return ordersService.updateOrderInfoStatus(orderInfoId);
    }

    /**
     * 子订单-修改地址
     */
    @PostMapping("/updateAddress")
    public CommonResult updateAddress(@RequestBody ReceiveAddressRequest request){
        return ordersService.updateAddress(request);
    }

    /**
     * 子订单-添加备注
     */
    @GetMapping("/insertOrderRemark")
    public CommonResult insertOrderRemark(@RequestParam("childOrderNo") String childOrderNo,
                                          @RequestParam("serviceRemark") String serviceRemark,
                                          @RequestParam(value = "orderInfoId", required = false) Integer orderInfoId) {
        boolean i = ordersService.insertOrderRemark(childOrderNo,serviceRemark, orderInfoId);
        if (i == true) {
            return CommonResult.success("添加成功");
        }
        return CommonResult.failed("添加失败");
    }

    /**
     * 订单详情 - 导出
     */
    @PostMapping("/findAllOrderInfo")
    public CommonResult findAllOrderInfo(@RequestBody OrdersInfoRequest ordersInfoRequest) {
        return CommonResult.success(ordersService.findAllOrderInfo(ordersInfoRequest));
    }

    /**
     * 子订单导出
     */
    @PostMapping("/exportOrderInfo")
    public CommonResult exportOrderInfo(@RequestBody OrdersInfoRequest ordersInfoRequest) throws Exception{
        ordersInfoRequest.setAdminId(UserUtil.getAdminId());
        if (null ==ordersInfoRequest.getStartTime()  || null == ordersInfoRequest.getEndTime()) {
            throw new ApiException("订单导出需要选择订单开始时间和结束时间");
        }
        if (null !=ordersInfoRequest.getStartTime()  && null != ordersInfoRequest.getEndTime()) {
            long between = DateUtil.between(ordersInfoRequest.getStartTime(), ordersInfoRequest.getEndTime(), DateUnit.DAY);
            if (between > 31) {
                throw new ApiException("订单导出时间跨度不能超过31天");
            }
        }
        return CommonResult.success(ordersService.exportOrderInfo(ordersInfoRequest));
    }

    /**
     * 查询导出子订单的导出记录
     * @param queryOrderRecordRequest
     * @return
     */
    @PostMapping("/getExportOrderInfoRecordList")
    public CommonResult getExportOrderInfoRecordList(@RequestBody QueryOrderRecordRequest queryOrderRecordRequest) {
        queryOrderRecordRequest.setExportType(2);
        queryOrderRecordRequest.setAdminId(UserUtil.getAdminId());
        CommonPage commonPage = ordersService.getExportOrderInfoRecordList(queryOrderRecordRequest);
        return CommonResult.success(commonPage);
    }

    /**
     * 查询供应链订单列表
     * @param request
     * @return
     */
    @PostMapping("/supplyChainOrderList")
    public CommonResult querySupplyChainOrderList(@RequestBody SupplyChainOrderListRequest request) {
        boolean isLimitRole = ordersService.checkIsLimitRole();
        request.setIsLimitRole(isLimitRole);
        String resultJson =
                HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/getBankerOrderList",
                        JSONObject.toJSONString(request), supplyApiConfig.getHeadsMap());
        CommonResult commonResult = JSONObject.parseObject(resultJson, CommonResult.class);
        return commonResult;
    }

    /**
     * 导出供应链订单列表
     * @param request
     * @return
     */
    @PostMapping("/exportSupplyChainOrderList")
    public CommonResult exportSupplyChainOrderList(@RequestBody SupplyChainOrderListRequest request) {
        boolean isLimitRole = ordersService.checkIsLimitRole();
        request.setIsLimitRole(isLimitRole);
        String resultJson =
                HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/newExportBankerOrderList",
                        JSONObject.toJSONString(request), supplyApiConfig.getHeadsMap());
        CommonResult commonResult = JSONObject.parseObject(resultJson, CommonResult.class);
        return commonResult;
    }

    /**
     * 查询导出应链订单记录
     */
    @PostMapping("/getBankerExportRecordList")
    public CommonResult getBankerExportRecordList(@RequestBody QueryOrderRecordRequest request) {
        request.setExportType(2);
        String resultJson =
                HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/getBankerExportRecordList",
                        JSONObject.toJSONString(request), supplyApiConfig.getHeadsMap());
        CommonResult commonResult = JSONObject.parseObject(resultJson, CommonResult.class);
        return commonResult;
    }


    /**
     * @Description 下载excel文件
     * @Version 1.0
     **/
    @GetMapping("/downloadExcel")
    public void download(String fileName, HttpServletResponse response) {
        ordersService.downloadExcel(fileName,response);
    }

    @GetMapping("/downloadNewExcel")
    public void downloadNewExcel(Integer id, HttpServletResponse response) {
        ordersService.downloadNewExcel(id,response);
    }

    /**
     * @Description 校验补单
     * @Version 1.0
     **/
    @GetMapping("/reissueLogCheck")
    public CommonResult reissueLogCheck(String childOrderNo,Integer type) {
        return ordersService.reissueLogCheck(childOrderNo,type);
    }

    /**
     * 供应链订单编辑
     * @param orderExpressModifiedRequest
     * @return
     */
    @PostMapping("/fillEmptyExpress")
    public CommonResult fillEmptyExpress(@RequestBody OrderExpressModifiedRequest orderExpressModifiedRequest) {
        Admin admin = memberService.getAdmin();
        orderExpressModifiedRequest.setOperator(admin.getName());
        String resultJson =
                HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/fillEmptyExpress",
                        JSONObject.toJSONString(orderExpressModifiedRequest), supplyApiConfig.getHeadsMap());
        CommonResult commonResult = JSONObject.parseObject(resultJson, CommonResult.class);
        return commonResult;
    }

    /**
     * 查询物流公司
     * @return
     */
    @GetMapping("/getExpressList")
    public CommonResult getExpressList() {
        String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/order/getExpressList", new HashMap(), supplyApiConfig.getHeadsMap());
        CommonResult commonResult = JSONObject.parseObject(resultJson, CommonResult.class);
        return commonResult;
    }

    /**
     * 导入供应链订单快递信息
     * @param file
     * @return
     */
    @PostMapping("/importOrdersExpressInfo")
    public CommonResult updateOrdersExpressInfo(MultipartFile file) {
        // 导入订单
        Sheet sheet = new Sheet(1, 1, ImportOrdersExpressNewRequest.class);
        try {
            List<Object> list = EasyExcelFactory.read(new BufferedInputStream(file.getInputStream()), sheet);
            List<ImportOrdersExpressNewRequest> requestList = new ArrayList<>();
            list.stream().forEach(item -> {
                ImportOrdersExpressNewRequest request = (ImportOrdersExpressNewRequest) item;
                requestList.add(request);
            });
            SupplyChainImportOrdersExpressListRequest request = new SupplyChainImportOrdersExpressListRequest();
            request.setList(requestList);
            String resultJson =
                    HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/importOrdersExpressInfo",
                            JSONObject.toJSONString(request), supplyApiConfig.getHeadsMap());
            CommonResult commonResult = JSONObject.parseObject(resultJson, CommonResult.class);
            return commonResult;
        } catch (IOException e) {
            log.error("===导入物流订单号失败==={}", e);
        }
        return CommonResult.failed("导入失败");
    }

    /**
     * 供应链订单详情
     * @param orderNo
     * @return
     */
    @GetMapping("/findBankerOrderInfoByNo")
    public CommonResult findBankerOrderInfoByNo(@RequestParam(value = "childOrderNo", required = false) String childOrderNo,
                                                @RequestParam("orderNo") String orderNo) {
        Map<String, String> map = new HashMap();
        map.put("childOrderNo", childOrderNo);
        map.put("orderNo", orderNo);
        String resultJson =
                HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/order/findBankerOrderInfoByNo",
                        map, supplyApiConfig.getHeadsMap());
        CommonResult commonResult = JSONObject.parseObject(resultJson, CommonResult.class);
        return commonResult;
    }

    /**
     * 订单同步供应商接口
     * @param orderId
     * @return
     */
    @GetMapping("/ordersUpload")
    public CommonResult ordersUpload(@RequestParam Integer orderId){
        mallClient.ordersUpload(orderId);
        return CommonResult.success();
    }

    /**
     * 批量推送
     * @param request
     * @return
     */
    @PostMapping("/ordersUploadBatch")
    public CommonResult orderUploadByBatch(@RequestBody OrderUploadToSupplychainRequest request) {
        List<Integer> orderIds = request.getOrderIds();
        if (!CollectionUtils.isEmpty(orderIds)) {
            orderIds.stream().forEach(orderId -> {
                mallClient.ordersUpload(orderId);
            });
        }
        return CommonResult.success();
    }

    /**
     * 刷新微信支付状态(8点到现在的订单)
     */
    @GetMapping("/updateWxAppOrdersStatus")
    public CommonResult updateWxAppOrdersStatus(){
        return ordersService.updateWxAppOrdersStatus();
    }

    /**
     * 刷新支付宝支付状态(8点到现在的订单)
     */
    @GetMapping("/updateAliPayAppOrdersStatus")
    public CommonResult updateAliPayAppOrdersStatus() {
        return ordersService.updateAliPayAppOrdersStatus();
    }


    /**
     * 设置订单为已完结
     * @param childOrderNo 子订单号
     * @param status 0-设置为未完成  1-设置为已完成
     * @return
     */
    @GetMapping("/setOrdersFinished")
    public CommonResult setOrdersFinished(String childOrderNo,String status) {
        Map map = new HashMap();
        map.put("childOrderNo",childOrderNo);
        map.put("status",status);
        String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/order/setOrdersFinished",
                        map, supplyApiConfig.getHeadsMap());
        CommonResult commonResult = JSONObject.parseObject(resultJson, CommonResult.class);

        //同步支付宝订单状态（）;
        try{
            OrdersPayResponse ordersPay = ordersPayMapper.queryByChildOrderNo(childOrderNo);
            if (!org.springframework.util.StringUtils.isEmpty(ordersPay.getTradeType()) && "aliPay-jsApi".equals(ordersPay.getTradeType())) {
                AliPayOrderSyncRequest request = new AliPayOrderSyncRequest();
                request.setCreateTime(ordersPay.getOrderCreateTime());
                request.setOrderId(ordersPay.getOrderId().toString());
                request.setOrderStatus("FINISHED");
                request.setUserId(ordersPay.getUserId());
                request.setChildId(ordersPay.getChildId());
                request.setProductName(ordersPay.getProductName());
                request.setProductImg(ordersPay.getProductImg());
                request.setOrderNo(ordersPay.getOrderNo());
                mallClient.syncAliPayOrder(request);
            }
        }catch (Exception e) {
            log.error("同步支付宝订单状态失败：{}",e.getMessage());
        }

        return commonResult;
    }

    /**
     * 获取订单详情
     * @param childOrderNo 子订单号
     * @return
     */
    @GetMapping("/getOrdersInfoByChildOrderNo")
    public CommonResult<OrdersInfoResponse> getOrdersInfoByChildOrderNo(String childOrderNo) {
        OrdersInfoResponse response = customerDao.getOrdersInfoByChildOrderNo(childOrderNo);
        return CommonResult.success(response);
    }
}
